/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.neuronbit.businessflow.intellij.dialog;

import com.neuronbit.businessflow.intellij.Json;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.TreeStructureProvider;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.util.TreeChooser;
import com.intellij.ide.util.treeView.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.ui.DoubleClickListener;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SideBorder;
import com.intellij.ui.TreeUIHelper;
import com.intellij.ui.tree.AsyncTreeModel;
import com.intellij.ui.tree.StructureTreeModel;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.AstLoadingFilter;
import com.intellij.util.concurrency.AppExecutorUtil;
import com.intellij.util.indexing.DumbModeAccessType;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.*;

import static com.neuronbit.businessflow.intellij.dialog.PsiFieldDialog.NodeType.*;

/**
 * This is dialog box for selecting methods of classes
 */
public class PsiFieldDialog extends DialogWrapper {
    private final JsonArray returns;
    private final JsonArray flowParams;
    private final String defaultSelectedValue;
    private final String paramType;
    private final @Nullable PsiClass paramClass;
    private JPanel panel = new JPanel(new BorderLayout());
    private final Project myProject;
    private MyTreeNode mySelectedClass;
    private StructureTreeModel<? extends AbstractTreeStructureBase> myModel;

    private final @NotNull TreeChooser.Filter<MyTreeNode> myClassFilter;
    private Tree myTree;
    private final @NotNull Comparator<? super NodeDescriptor<?>> myComparator;

    /**
     * Instantiates a new Psi field dialog.
     *
     * @param project the project
     * @param params  the params
     */
    public PsiFieldDialog(@Nullable Project project, String params) {
        super(project);
        this.myProject = project;
        setModal(true);
        init();
        panel.setOpaque(false);

        myComparator = AlphaComparator.INSTANCE;
        myClassFilter = allFilter();

        Json json = new Json(params);
        returns = json.array("$.returns");
        defaultSelectedValue = json.read("$.value");
        flowParams = json.array("$.flowParams");
        paramType = json.read("$.paramType");
        if (StringUtils.isBlank(paramType)) {
            throw new RuntimeException("type of the parameter can not be null");
        }
        paramClass = JavaPsiFacade.getInstance(project).findClass(paramType, GlobalSearchScope.allScope(project));
        if (paramClass == null) {
            throw new RuntimeException("can not find param Type in the project and its dependencies, " + paramType);
        }
    }

    private TreeChooser.Filter<MyTreeNode> allFilter() {
        return node -> {
            String returnType = node.getValue().getClazzName();
            PsiClass returnClass = JavaPsiFacade.getInstance(myProject).findClass(returnType, GlobalSearchScope.allScope(myProject));
            if (returnClass == null) {
                return false;
            } else {
                return returnClass.equals(paramClass) || returnClass.isInheritor(paramClass, true);
            }
        };
    }

    @Override
    public void doOKAction() {
        super.doOKAction();
    }

    @Override
    public void doCancelAction() {
        super.doCancelAction();
        this.mySelectedClass = null;
    }

    /**
     * Gets selected.
     *
     * @return the selected
     */
    public String getSelected() {
        return getPsiMethodInfo(mySelectedClass);
    }

    private @NotNull ModalityState getModalityState() {
        return ModalityState.stateForComponent(getRootPane());
    }

    /**
     * Gets tree.
     *
     * @return the tree
     */
    protected Tree getTree() {
        return myTree;
    }

    /**
     * Calc selected class object.
     *
     * @return the object
     */
    protected @Nullable Object calcSelectedClass() {
        TreePath path = getTree().getSelectionPath();
        if (path == null) return null;
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
        if (!node.isLeaf()) {
            return null;
        }
        return getSelectedFromTreeUserObject(node);
    }

    /**
     * Gets selected from tree user object.
     *
     * @param node the node
     * @return the selected from tree user object
     */
    protected Object getSelectedFromTreeUserObject(DefaultMutableTreeNode node) {
        return node.getUserObject();
    }

    /**
     * The enum Node type.
     */
    public enum NodeType {
        /**
         * Root node type.
         */
        ROOT,
        /**
         * Task node type.
         */
        TASK,
        /**
         * Output node type.
         */
        OUTPUT,
        /**
         * Field node type.
         */
        FIELD;
    }

    /**
     * The type Node value.
     */
    @Getter
    public static class NodeValue {
        private final NodeType type;
        private final String name;
        private final String clazzName;
        private final String parentName;
        @Setter
        private String returnName;
        @Setter
        private String returnType;

        /**
         * Instantiates a new Node value.
         *
         * @param type       the type
         * @param parentName the parent name
         * @param name       the name
         * @param clazzName  the clazz name
         */
        public NodeValue(NodeType type, String parentName, String name, String clazzName) {
            this.type = type;
            this.parentName = parentName;
            this.name = name;
            this.clazzName = clazzName;
        }

        /**
         * Gets qualified name.
         *
         * @return the qualified name
         */
        public String getQualifiedName() {
            if (StringUtils.isNoneBlank(this.parentName)) {
                return this.parentName + "." + this.name;
            } else {
                return this.name;
            }
        }
    }

    /**
     * The type My tree node.
     */
    public class MyTreeNode extends AbstractTreeNode<NodeValue> {


        /**
         * Instantiates a new My tree node.
         *
         * @param project the project
         * @param value   the value
         */
        protected MyTreeNode(Project project, @NotNull NodeValue value) {
            super(project, value);
        }

        @Override
        public @NotNull Collection<? extends AbstractTreeNode<?>> getChildren() {
            ArrayList<AbstractTreeNode<?>> list = new ArrayList<>();
            if (this.getValue().getType() == NodeType.ROOT) {
                if (null != returns) {
                    for (JsonElement aReturn : returns) {
                        Json json1 = new Json(aReturn.toString());
                        String taskName = json1.read("$.name");
                        String outputName = json1.read("$.returns.returnName");
                        String outputType = json1.read("$.returns.returnType");
                        if (outputType == null) {
                            continue;
                        }
                        //TODO shunyun 2024/1/15:在生成赋值代码时，需要先判断一下 input 是 optional 还是实际参数类型，如果是实际参数类型，
                        // 还要检查类型是否匹配，同时还要进行 present 的判断
                        if (outputType.startsWith("java.util.Optional<")) {
                            //TODO shunyun 2024/1/15: 多层级泛型
                            outputType = StringUtils.substringBetween(outputType, "<", ">");
                        }

                        NodeValue value = new NodeValue(TASK, "", taskName, null);
                        value.setReturnName(outputName);
                        value.setReturnType(outputType);
                        list.add(new MyTreeNode(getProject(), value));
                    }
                }
                if (null != flowParams) {
                    for (JsonElement aReturn : flowParams) {
                        Json json1 = new Json(aReturn.toString());
                        String outputName = json1.read("$.paramName");
                        String outputType = json1.read("$.paramType");


                        if (outputType == null) {
                            continue;
                        }
                        //TODO shunyun 2024/1/15:在生成赋值代码时，需要先判断一下 input 是 optional 还是实际参数类型，如果是实际参数类型，
                        // 还要检查类型是否匹配，同时还要进行 present 的判断
                        if (outputType.startsWith("java.util.Optional<")) {
                            //TODO shunyun 2024/1/15: 多层级泛型
                            outputType = StringUtils.substringBetween(outputType, "<", ">");
                        }
                        NodeValue value = new NodeValue(FIELD, "flow.input", outputName, outputType);
                        value.setReturnName(outputName);
                        value.setReturnType(outputType);
                        list.add(new MyTreeNode(getProject(), value));
                    }
                }
            }
            if (this.getValue().getType() == TASK) {
                list.add(new MyTreeNode(getProject(), new NodeValue(OUTPUT, this.getValue().getQualifiedName(), this.getValue().getReturnName(), this.getValue().getReturnType())));
            }
            if (this.getValue().getType() == OUTPUT) {
                GlobalSearchScope scope = GlobalSearchScope.allScope(getProject());
                PsiClass psiClass = JavaPsiFacade.getInstance(getProject()).findClass(this.getValue().getClazzName(), scope);
                if (psiClass != null) {
                    if (psiClass.isEnum() || Objects.requireNonNull(psiClass.getQualifiedName()).startsWith("java.lang")) {
                        //do nothing
                    } else {
                        List<String> getterNames = Arrays.stream(psiClass.getAllMethods())
                                .map(PsiMethod::getName)
                                .filter(name -> name.startsWith("get"))
                                .toList();

                        list.addAll(Arrays.stream(psiClass.getAllFields())
                                .filter(m -> getterNames.contains("get" + StringUtils.capitalize(m.getName())))
                                .map(m -> new MyTreeNode(getProject(), new NodeValue(FIELD, this.getValue().getQualifiedName(), m.getName(), PsiTypesUtil.getPsiClass(m.getType()).getQualifiedName())))
                                .toList());
                    }
                }
            }
            //TODO shunyun 2024/1/16: field的嵌套
            return list;
        }

        @Override
        protected void update(@NotNull PresentationData presentationData) {
            AstLoadingFilter.disallowTreeLoading(() -> doUpdate(presentationData));
        }

        private void doUpdate(@NotNull PresentationData data) {
            ApplicationManager.getApplication().runReadAction(() -> {
//                if (!validate()) {
//                    return;
//                }
//
//                final PsiElement value = extractPsiFromValue();
//                LOG.assertTrue(value.isValid());
//
//                int flags = getIconableFlags();
//                Icon icon = null;
//                boolean deprecated = false;
//                try {
//                    icon = value.getIcon(flags);
//                }
//                catch (IndexNotReadyException ignored) {
//                }
//                try {
//                    deprecated = isDeprecated();
//                }
//                catch (IndexNotReadyException ignored) {
//                }
//
//                final Icon tagIcon;
//                final ColoredText tagText;
//                if (!TagManager.isEnabled()) {
//                    tagIcon = getBookmarkIcon(myProject, value);
//                    tagText = null;
//                }
//                else {
//                    var tagIconAndText = TagManager.getTagIconAndText(value);
//                    tagIcon = tagIconAndText.icon();
//                    tagText = tagIconAndText.coloredText();
//                }
//                data.setIcon(withIconMarker(icon, tagIcon));
                NodeValue value = getValue();
                data.setPresentableText(value.getName());
//                if (deprecated) {
//                    data.setAttributesKey(CodeInsightColors.DEPRECATED_ATTRIBUTES);
//                }
//                if (tagText != null) {
//                    var fragments = tagText.fragments();
//                    for (ColoredText.Fragment fragment : fragments) {
//                        data.getColoredText().add(new ColoredFragment(fragment.fragmentText(), fragment.fragmentAttributes()));
//                    }
//                    if (!fragments.isEmpty()) {
//                        data.getColoredText().add(new ColoredFragment(myName, getSimpleTextAttributes(data)));
//                    }
//                }
//                updateImpl(data);
//                data.setIcon(patchIcon(myProject, data.getIcon(true), getVirtualFile()));
//                CompoundProjectViewNodeDecorator.get(myProject).decorate(this, data);
//                updateTimestamp();
            });
        }
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        AbstractTreeStructureBase treeStructure = new AbstractTreeStructureBase(myProject) {

            @Override
            public @NotNull Object getRootElement() {
                return new MyTreeNode(myProject, new NodeValue(NodeType.ROOT, null, "root object", null));
            }

            @Override
            public void commit() {

            }

            @Override
            public boolean hasSomethingToCommit() {
                return false;
            }

            @Override
            public @Nullable List<TreeStructureProvider> getProviders() {
                TreeStructureProvider provider = new TreeStructureProvider() {

                    @Override
                    public @NotNull Collection<AbstractTreeNode<?>> modify(@NotNull AbstractTreeNode<?> abstractTreeNode,
                                                                           @NotNull Collection<AbstractTreeNode<?>> collection,
                                                                           ViewSettings viewSettings) {
                        return collection;
                    }

                    @Override
                    public @Nullable Object getData(@NotNull Collection<? extends AbstractTreeNode<?>> selected, @NotNull String dataId) {
                        return TreeStructureProvider.super.getData(selected, dataId);
                    }
                };
                return List.of(provider);
            }
        };

        myModel = new StructureTreeModel<>(treeStructure, getDisposable());
        myModel.setComparator(myComparator);
        myTree = new Tree(new AsyncTreeModel(myModel, getDisposable()));
        myTree.setRootVisible(false);
        myTree.setShowsRootHandles(true);
        myTree.expandRow(0);
        myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        myTree.setCellRenderer(new NodeRenderer());

        JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree);
        scrollPane.setPreferredSize(JBUI.size(500, 300));
        scrollPane.putClientProperty(UIUtil.KEEP_BORDER_SIDES, SideBorder.RIGHT | SideBorder.LEFT | SideBorder.BOTTOM);

        myTree.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (KeyEvent.VK_ENTER == e.getKeyCode()) {
                    doOKAction();
                }
            }
        });

        new DoubleClickListener() {
            @Override
            protected boolean onDoubleClick(@NotNull MouseEvent event) {
                TreePath path = myTree.getPathForLocation(event.getX(), event.getY());
                if (path != null && myTree.isPathSelected(path)) {
                    doOKAction();
                    return true;
                }
                return false;
            }
        }.installOn(myTree);

        myTree.addTreeSelectionListener(__ -> handleSelectionChanged());

        TreeUIHelper.getInstance().installTreeSpeedSearch(myTree);

        final JPanel dummyPanel = new JPanel(new BorderLayout());

        dummyPanel.add(scrollPane, BorderLayout.CENTER);
        dummyPanel.setMinimumSize(new Dimension(500, 400));
        dummyPanel.setMaximumSize(new Dimension(500, 400));

        return dummyPanel;
    }

    private void handleSelectionChanged() {
        Object selected = calcSelectedClass();
        if (selected == null) {
            setOKActionEnabled(false);
        } else {
            MyTreeNode selectedClass = (MyTreeNode) selected;
            mySelectedClass = selectedClass;
            ReadAction
                    .nonBlocking(() -> DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode(() -> myClassFilter.isAccepted(selectedClass)))
                    .finishOnUiThread(getModalityState(), isAccepted -> setOKActionEnabled(selected != null && isAccepted))
                    .submit(AppExecutorUtil.getAppExecutorService());
        }
    }

    /**
     * Gets psi method info.
     *
     * @param node the node
     * @return the psi method info
     */
    protected String getPsiMethodInfo(MyTreeNode node) {
        if (null == node) {
            return "";
        }
        return node.getValue().getQualifiedName();
    }
}
